import { useState, useEffect, useRef } from 'react'
import DarkBtn from '../../../../../../common/DarkBtn';
import { BarChartOutlined, CloseOutlined, FullscreenExitOutlined, FullscreenOutlined } from '@ant-design/icons';
import DarkCard from '../../../../../../common/DarkCard';
import { Button, Col, Row, Select, Table } from 'antd';
import usePanelKey from '../../../../../../common/BusinessMap/usePanelKey';
import useBusinessMap from '../../../../../../common/BusinessMap/useBusinessMap';
import useMapGlobal from '../../../../../../common/BusinessMap/useMapGlobal';
import LittleTitle from '../../../../../../common/LittleTitle';
import * as echarts from 'echarts';
import echartsOptions from './echartsOptions';
import CztApi from '../../../../../../../utils/apis/CztApi';
import ScrollTable from '../../../../../../common/ScrollTable';
import { navByWkt } from '../../../../../../../utils/helper/mapHelper';
import { cacheDatas } from '../../../../../../../utils/constant';
import JzzyApi from '../../../../../../../utils/apis/JzzyApi';


export default function Stat(props) {

    const [mapGlobal] = useMapGlobal();
    const { visibleLayers } = mapGlobal;
    console.log(mapGlobal)
    const [panelKey, setPanelKey] = usePanelKey();
    const [statData, setStatData] = useState();
    const map = useBusinessMap();
    const chartRef = useRef();
    const [selectedName, setSelectedName] = useState();
    const [tableDatas, setTableDatas] = useState()

    const isVisible = panelKey === 'yzt-stat';
    const rootRef = useRef();
    const echartsRef = useRef();

    useEffect(() => {
        if (isVisible && statData) {
            const chart = echartsRef.current = echarts.init(chartRef.current);
            chart.setOption(echartsOptions(statData))
        }
    }, [isVisible, statData])

    // useEffect(() => {
    //     if (selectedName && visibleLayers) {
    //         const layer = visibleLayers.find(l => l.get('name') === selectedName);
    //         if (layer) {
    //             setTableDatas(layer.getSource().getFeatures().map(f => {
    //                 return f.getProperties();
    //             }))
    //         }
    //     }
    // }, [selectedName, visibleLayers])
    // console.log('tableDatas',tableDatas)

    useEffect(() => {
        if (selectedName) {
            const targetLayer = visibleLayers?.find(l => l.get('name') === selectedName);
            if (!targetLayer) {
                setSelectedName(null);
                if (echartsRef.current) {
                    echartsRef.current.dispose()
                }
                setTableDatas([])
            }
        }
    }, [visibleLayers, selectedName])


    return <>
        <DarkBtn icon={<BarChartOutlined />} title={"统计"} onClick={e => {
            setPanelKey('yzt-stat')
        }}></DarkBtn>
        {<DarkCard style={{
            position: 'absolute',
            right: '48px',
            width: '300px',
            top: '0px',
            bottom: '20px',
            pointerEvents: 'auto',
            borderRadius: 8,
            display: panelKey === 'yzt-stat' ? 'flex' : 'none'
        }} className="layout-v">
            <div style={{
                fontSize: 20,
                fontWeight: "bold",
                borderBottom: "1px solid #eee",
                paddingBottom: 12,
                marginBottom: 12
            }} className='layout-h center'>
                <div className='fill w0'>数据统计</div>
                <div>
                    <Button size="small" icon={<CloseOutlined />} style={{
                        // color: "#fff"
                        background: "#00000000"
                    }} onClick={e => {
                        setPanelKey(null)
                    }} />
                </div>
            </div>
            <Row justify="center" align={"middle"}>
                <Col>已打开图层：</Col>
                <Col flex={1} style={{
                    width: 0
                }}>
                    <Select style={{
                        width: '100%'
                    }} value={selectedName} options={visibleLayers?.map(layer => {
                        return {
                            label: layer.get('name'),
                            value: layer.get('name')
                        }
                    })} onChange={value => {
                        setSelectedName(value)
                        const layer = visibleLayers.find(l => l.get('name') === value);
                        if (layer) {
                            const datas = cacheDatas[value];
                            setTableDatas((datas || []).map(d => {
                                return {
                                    ...d,
                                    layerName: value
                                }
                            }))
                            switch (layer.get('dl')) {
                                case 'zhfx':
                                    CztApi.stat(value).then(data => {
                                        setStatData(data)
                                    })
                                    break;
                                case 'czt':
                                    CztApi.groupByXl(value).then(resp => {
                                        setStatData(resp.data.map(d => {
                                            return {
                                                name: d.xzqhmc || '无',
                                                value: d.number
                                            }
                                        }))
                                    })
                                    break;
                                case 'jzzy':
                                    JzzyApi.groupByXl(value).then(resp => {
                                        setStatData(resp.data.map(d => {
                                            return {
                                                name: d.xzqhmc || '无',
                                                value: d.number
                                            }
                                        }))
                                    })
                                    break;
                                default:
                            }
                        }
                    }}>
                    </Select>
                </Col>
            </Row>
            <div className='fill layout-v'>
                <div className='fill h0 layout-v'>
                    <LittleTitle>区域统计</LittleTitle>
                    <div className='fill h0' style={{
                        overflow: 'auto'
                    }}>
                        <div ref={chartRef} className="wh100"></div>
                    </div>
                </div>
                <div className='fill h0 layout-v'>
                    <LittleTitle>详细列表</LittleTitle>
                    <div ref={rootRef} className="fill h0">
                        <ScrollTable otherHeight={120} parentNode={rootRef.current} className='fill' columns={[{
                            title: '名称',
                            // dataIndex: "yhmc",

                            render: (text, record) => {
                                return record.cztmc || record.jzzymc || record.yhmc
                            }
                        }, {
                            width: 70,
                            align: "center",
                            render: (text, record) => {
                                return <Button size="small" type="link" onClick={e => {
                                    map.dispatchEvent({
                                        type: 'yzt.detail',
                                        item: record
                                    })
                                    record.geom && navByWkt(record.geom, map)
                                }}>详情</Button>
                            }
                        }]} size="small" dataSource={tableDatas || []}
                            pagination={{
                                pageSize: 5
                            }}
                        />
                    </div>
                </div>
            </div>
        </DarkCard>}
    </>;
}